package com.trade.module.base.controller;

import com.trade.module.base.entity.Dictionary;
import com.trade.module.base.entity.SystemLog;
import com.trade.module.base.service.DictionaryService;
import com.trade.module.base.service.SystemLogService;
import com.trade.module.base.vo.UserVo;
import com.trade.system.sysrun.DictionaryUtil;
import com.trade.common.utils.*;
import com.trade.module.base.vo.DictionaryVo;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * Class Description: 数据字典控制类
 *
 * @Version v1.0 2017/5/5 0:37
 * @JDK version 1.8.0_51
 * @Author zfb
 */
@Log4j
@Controller
@RequestMapping(value = "/base/dictionary")
public class DictionaryController extends BaseController {

    /***Field description：注入数据字典服务层*/
    @Autowired
    private DictionaryService dictionaryService;
    /***Field description：注入系统日志服务层*/
    @Autowired
    private SystemLogService systemLogService;

    /**
     * Method description：新增字典
     * Version:V1.0     （已改）
     * Author:lwl
     * Date:2016.03.16 at 05:29:16 CST
     *
     * @param dictionaryVo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "",method = RequestMethod.POST)
    public ResponseBean save(@RequestBody DictionaryVo dictionaryVo, HttpServletRequest request) {
        //获取当前操作人信息
        UserVo currentUser = getCurrentUser();
        String currentUserId = (currentUser != null) ? currentUser.getId() : "";
        String account = (currentUser != null) ? currentUser.getAccount() : "";
        dictionaryVo.setModifyId(currentUserId);
        dictionaryVo.setCreaterId(currentUserId);
        Dictionary dictionaryPo = dictionaryService.save(dictionaryVo);
        if (dictionaryPo != null){
            //打印日志
            SystemLog sysLog = LogUtil.buildeLogBean(Dictionary.class, LogUtil.LogLevel.info,
                    LogUtil.CRUDType.create, LogUtil.OperatRsult.success, currentUserId,
                    account, dictionaryPo.getId(), NetUtil.getIp(request), "添加字典成功");
            systemLogService.save(sysLog);
            log.info(LogUtil.getLogJsonFromBean(sysLog).toString());
            // 设置返回信息
            return new ResponseBean(ResponseUtil.MODIFY_OK_201);
        }else{
            //打印日志
            SystemLog sysLog = LogUtil.buildeLogBean(Dictionary.class, LogUtil.LogLevel.error,
                    LogUtil.CRUDType.create, LogUtil.OperatRsult.failure, currentUserId,
                    account, "", NetUtil.getIp(request), "添加字典失败");
            systemLogService.save(sysLog);
            log.error(LogUtil.getLogJsonFromBean(sysLog).toString());
            // 设置返回信息
            return new ResponseBean(ResponseUtil.VERIFY_ERROR_422,"字典编码已存在");
        }
    }

    /**
     * Method description：根据字典类型编码获取字典值集合
     *
     * @param dicCode 字典编码
     * @return List<Dictionary>>
     */
    @ResponseBody
    @RequestMapping(value = "/getByCode/{dicCode}", method = RequestMethod.GET)
    public ResponseBean<List<Dictionary>> getByCode(@PathVariable String dicCode, HttpServletRequest request) {
        //获取当前操作人信息
        UserVo currentUser = getCurrentUser();
        String currentUserId = (currentUser != null) ? currentUser.getId() : "";

        // 存储字典
        List<Dictionary> dictionaryList = DictionaryUtil.getInstance().getDicValueListByDicTypeCode(dicCode);
        // 设置返回信息
        if (null != dictionaryList) {
            SystemLog sysLog = LogUtil.buildeLogBean(Dictionary.class, LogUtil.LogLevel.info, LogUtil.CRUDType.read, LogUtil.OperatRsult.success
                    , currentUserId, (currentUser != null) ? currentUser.getAccount() : "", "", NetUtil.getIp(request), "根据字典编码查询字典成功,dicCode=" + dicCode);
            systemLogService.save(sysLog);
            log.info(LogUtil.getLogJsonFromBean(sysLog).toString());
            return new ResponseBean<>(ResponseUtil.SELECT_OK_200, dictionaryList);
        } else {
            SystemLog sysLog = LogUtil.buildeLogBean(Dictionary.class, LogUtil.LogLevel.error, LogUtil.CRUDType.read, LogUtil.OperatRsult.failure
                    , currentUserId, (currentUser != null) ? currentUser.getAccount() : "", "", NetUtil.getIp(request), "根据字典编码查询字典失败,dicCode=" + dicCode);
            systemLogService.save(sysLog);
            log.error(LogUtil.getLogJsonFromBean(sysLog).toString());
            return new ResponseBean<>(ResponseUtil.NOT_EXIST_ERROR_404, new ArrayList<Dictionary>());
        }
    }

    /**
     * 根据条件分页查询字典数据
     *
     * @param start              number类型,第一条数据的起始位置，当前数据集的开始点（0为基数）。
     * @param length             当前页面要显示的数据条数
     * @param draw               number类型,请求次数计数器，每次发送给服务器后原封返回，因为请求是异步的，
     *                           为了确保每次请求都能对应到服务器返回到的数据。
     * @param sortJsonArray      排序的json数组，格式为[{property:"排序字段名",direction:"ASC/DESC"}]，
     *                           null、空字符串及[]将被认为是不进行排序
     * @param conditionJsonArray 查询条件的json数组，格式为[{property:"字段名",option:"操作类型",value:"值",propertytype:"数据类型"}]
     *                           其中option的值有EQ(等于), IN(在值数组中), ISNULL(非空), LIKE(包含), GT(大于), LT(小于), GTE(大于等于),
     *                           LTE(小于等于), NE(不等于),LIKEIGNORE(包含，忽略大小写)
     *                           propertytype为DATETIME或DATE，DATETIME值格式为YYYY-MM-dd HH:mm:ss，DATE值格式为YYYY-MM-dd
     *                           <p/>
     *                           conditionJsonArray为null、空字符串及[]将被认为是不进行条件过滤
     * @return ResponsePaging
     */
    @ResponseBody
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ResponsePaging<List<Dictionary>> list(@RequestParam(defaultValue = "-1") Integer start,
                                                 @RequestParam(defaultValue = "10") Integer length,
                                                 @RequestParam String draw,
                                                 @RequestParam(defaultValue = "") String sortJsonArray,
                                                 @RequestParam(defaultValue = "") String conditionJsonArray) {
        ResponsePaging<List<Dictionary>> responsePaging = dictionaryService.findDictionaryPageByCondition(start/length,
                length,sortJsonArray,conditionJsonArray);
        responsePaging.setDraw(Integer.parseInt(draw));
        return responsePaging;
    }

    /**
     * Method description：根据id来删除字典数据
     *
     * @param id 字典id
     * @return ResponseBean
     */
    @ResponseBody
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public ResponseBean deleteById(@PathVariable String id, HttpServletRequest request) {
        //获取当前操作人信息
        UserVo currentUser = getCurrentUser();
        String currentUserId = (currentUser != null) ? currentUser.getId() : "";
        String account = (currentUser != null) ? currentUser.getAccount() : "";
        // 删除数据
        int changeNum = dictionaryService.deleteById(id,currentUserId);

        //打印日志,设置返回信息
        if (changeNum > 0) {
            SystemLog sysLog = LogUtil.buildeLogBean(Dictionary.class, LogUtil.LogLevel.info,
                    LogUtil.CRUDType.delete, LogUtil.OperatRsult.success,currentUserId,account,
                    id, NetUtil.getIp(request), "删除字典数据成功");
            systemLogService.save(sysLog);
            log.info(LogUtil.getLogJsonFromBean(sysLog).toString());
            return new ResponseBean(ResponseUtil.DELETE_OK_204);
        } else {
            SystemLog sysLog = LogUtil.buildeLogBean(Dictionary.class, LogUtil.LogLevel.error,
                    LogUtil.CRUDType.delete, LogUtil.OperatRsult.failure, currentUserId,account,
                    id, NetUtil.getIp(request), "删除字典数据失败");
            systemLogService.save(sysLog);
            log.error(LogUtil.getLogJsonFromBean(sysLog).toString());
            return new ResponseBean(ResponseUtil.NOT_EXIST_ERROR_404);
        }
    }

    /**
     * Method description：根据id查询字典
     *
     * @param id 字典id
     * @return ResponseBean
     */
    @ResponseBody
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public ResponseBean<DictionaryVo> getById(@PathVariable String id, HttpServletRequest request) {
        //获取当前操作人信息
        UserVo currentUser = getCurrentUser();
        String currentUserId = (currentUser != null) ? currentUser.getId() : "";
        String account = (currentUser != null) ? currentUser.getAccount() : "";
        DictionaryVo dictionaryVo = dictionaryService.getById(id);
        //打印日志,设置返回信息
        if (dictionaryVo != null) {
            SystemLog sysLog = LogUtil.buildeLogBean(Dictionary.class, LogUtil.LogLevel.info,
                    LogUtil.CRUDType.read, LogUtil.OperatRsult.success,currentUserId,account,
                    id, NetUtil.getIp(request), "查询字典数据成功");
            systemLogService.save(sysLog);
            log.info(LogUtil.getLogJsonFromBean(sysLog).toString());
            return new ResponseBean<DictionaryVo>(ResponseUtil.SELECT_OK_200,dictionaryVo);
        } else {
            SystemLog sysLog = LogUtil.buildeLogBean(Dictionary.class, LogUtil.LogLevel.error,
                    LogUtil.CRUDType.read, LogUtil.OperatRsult.failure, currentUserId,account,
                    id, NetUtil.getIp(request), "查询字典数据失败");
            systemLogService.save(sysLog);
            log.error(LogUtil.getLogJsonFromBean(sysLog).toString());
            return new ResponseBean<DictionaryVo>(ResponseUtil.NOT_EXIST_ERROR_404);
        }
    }
}
